﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace DusonFramework.Core.Web
{
    /// <summary>
    /// 反射类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public sealed class Reflector<T> where T : class
    {
        /// <summary>
        /// 通过反射创建实体
        /// </summary>
        /// <param name="classFullName">类的全名</param>
        /// <param name="dllName">dllName</param>
        /// <returns></returns>
        public static T Create(string classFullName, string dllName)
        {
            return Create(classFullName, dllName, true);
        }

        /// <summary>
        /// 通过反射创建实体
        /// </summary>
        /// <param name="classFullName">类的全名</param>
        /// <param name="dllName">dllName</param>
        /// <param name="cacheFlag">是否从缓存中读取</param>
        /// <returns></returns>
        public static T Create(string classFullName, string dllName, bool cacheFlag)
        {
            T objType = null;
            if (cacheFlag)
            {
                objType = (T)Cacher.GetCache(classFullName);
                if (objType == null)
                {
                    objType = (T)Assembly.Load(dllName).CreateInstance(classFullName);//反射创建
                    Cacher.SetCache(classFullName, objType);
                }
            }
            else
            {
                objType = (T)CreateAssembly(dllName).CreateInstance(classFullName);//反射创建
            }
            return objType;
        }

        /// <summary>
        /// 创建Assembly
        /// </summary>
        /// <param name="dllName">dllName</param>
        /// <returns></returns>
        public static Assembly CreateAssembly(string dllName)
        {
            Assembly obj = (Assembly)Cacher.GetCache(dllName);
            if (obj == null)
            {
                obj = Assembly.Load(dllName);
                Cacher.SetCache(dllName, obj);
            }
            return obj;
        }
    }
}
